package fr.cephb.joperon.core.db;


import com.sleepycat.db.DatabaseEntry;
import com.sleepycat.db.DatabaseException;

import fr.cephb.berkeley.DBUtils;
import fr.cephb.joperon.core.Operon;
import fr.cephb.joperon.core.db.base.BasePrjFinDB;
import fr.cephb.joperon.core.entities.PrjFin;
import fr.cephb.joperon.core.iterator.AbstractIterator;
import fr.cephb.joperon.core.iterator.DatabaseValueIterator;
import fr.cephb.joperon.core.iterator.EqualRangeIterator;
import fr.cephb.joperon.core.iterator.FilterIterator;

public class PrjFinDB extends BasePrjFinDB
	{
	
	
	
	public PrjFinDB(Operon operon) {
		super(operon);
	}
	
	
	public PrjFin findByFix(String projectId,String fix)throws DatabaseException
		{
		DatabaseValueIterator<PrjFin> iter=null;
		try
			{
			iter=listValues(projectId);
			while(iter.hasNext())
				{
				PrjFin o=iter.next();
				if(fix.equals(o.getFix()))
					{
					return o;
					}
				}
			}
		catch(DatabaseException err)
			{
			throw err;
			}
		finally
			{
			if(iter!=null) iter.close();
			}
		return null;
		}
	
	
	public String nextFix(String projectId, PrjFin.Target target)
		throws DatabaseException
		{
		int n=1;
		while(true)
			{
			String key=target.getPrefix()+n;
			DatabaseValueIterator<PrjFin> iter=null;
			try
				{
				iter=listValues(projectId);
				while(iter.hasNext())
					{
					PrjFin o=iter.next();
					if(key.equals(o.getFix()))
						{
						key=null;
						break;
						}
					}
				if(key!=null) return key;
				}
			catch(DatabaseException err)
				{
				throw err;
				}
			finally
				{
				if(iter!=null) iter.close();
				}
			++n;
			}
		}

	public AbstractIterator<PrjFin> listProjectsById(String pid)
		throws DatabaseException
		{
		DatabaseEntry key= new DatabaseEntry(DBUtils.string2CString(pid));
		EqualRangeIterator iter1= new EqualRangeIterator(cursor(),key);
		return new DatabaseValueIterator<PrjFin>(iter1)
			{
			@Override
				protected PrjFin extractFromEntries(DatabaseEntry key,
						DatabaseEntry value) throws DatabaseException {
					return  new PrjFin(value);
					}
			};
		}
	
	
	public AbstractIterator<PrjFin> listProjectsByIdAndTarget(String pid,PrjFin.Target target)
	throws DatabaseException
		{
		return new FilterIterator<PrjFin, PrjFin.Target>(listProjectsById(pid),target)
			{
			@Override
			public boolean accept(PrjFin object)
				{
				if(object==null || getUserValue()==null) return false;
				return this.getUserValue()== object.getTarget();
				}
			};
		}
	
	
	public static void main(String[] args) {
		Operon op=null;
		PrjFinDB db=null;
		try {
			op= Operon.newInstance();
			db= new PrjFinDB(op);
			db.open();
			ValueIterator iter=db.listValues();
			while(iter.hasNext())
				{
				PrjFin o=iter.next();
				System.err.println(o);
				}
			iter.close();
		} catch (Exception e) {
			e.printStackTrace();
			}
		finally
			{
			if(db!=null) db.safeClose();
			if(op!=null) op.safeClose();
			}
		}
	
}
